﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using FCS.GlobalComponents;
using System.Net;
using FCS.Pattern.FountainConnection;
using System.IO;
using FCS.Communication;

namespace FCS.Pattern
{
    /// <summary>
    /// This class abstracts communication with the cRIO for control over the fountain valves
    /// </summary>
    public class FountainController : Controller
    {

        int _patternIndex = 0; // indicates the currently running pattern

        bool _noPatternsFound = false;

        /// <summary>
        /// Reads the security code, patterns, and restristed valves off disk and sends them to the server
        /// </summary>
        public FountainController()
            : base()
        {
            StreamReader sr = new StreamReader(@"C:\FountainData\patterncode.txt");
            _code = sr.ReadLine();
            sr.Close();
            sr.Dispose();
            SetDefaultCRIOAddress();


            _eventLogWriter = new EventLogWriter("Default Pattern Service");

            // read in the patterns
            try
            {
                DirectoryInfo di = new DirectoryInfo(@"C:\FountainData\Fountain Patterns");
                ReadPatterns(di);
            }
            catch (Exception e)
            {
                _eventLogWriter.WriteToLog(System.Diagnostics.EventLogEntryType.Error, "An error occured when reading in the patterns.\n" + e.Message + "\n\nInner Exception:\n" + e.InnerException);
            }
            
            // read in the restricted valves
            string folderPath = @"C:\FountainData\RestrictedPatternValves.txt";
            try
            {
                // Read in restirected valves
                StreamReader sr2 = new StreamReader(folderPath);
                List<string> restricted = new List<string>();
                while (!sr2.EndOfStream)
                {
                    restricted.Add(sr2.ReadLine());
                }
                // Send restricted valves
                AddRestrictedValves(restricted, FCS.GlobalComponents.CommandPriority.patterns);
            }
            catch (IOException)
            {
                EventLogWriter elw = new EventLogWriter("FountainController");
                string message = "Failed to open restriced valve file " + folderPath + " in Fountain Controller! Killing process to prevent damage to valves.";
                elw.WriteToLog(System.Diagnostics.EventLogEntryType.FailureAudit, message);

                throw new ApplicationException(message);
            }
        }

        /// <summary>
        /// Read the pattern in from file and execute it
        /// </summary>
        public void RunNextPattern()
        {
            _patternIndex++;

            if (_patterns.Count == 0 && !_noPatternsFound)
            {
                if (_noPatternsFound)
                {
                    _noPatternsFound = true;
                    _eventLogWriter.WriteToLog(System.Diagnostics.EventLogEntryType.Error, "The pattern service was unable to load the patterns");
                }
                return;
            }

            _patternIndex %= _patterns.Count;

            Pattern p = _patterns.ElementAt(_patternIndex);
            PlayPattern(p, CommandPriority.patterns);

            lock (_monitor)
            {
                _patternIsRunning = true;
            }
        }
    }
}
